package com.shujia.hbase;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo6PhoenixJDBC {

    @Test
    public void query() throws Exception {
        //1、建立jdbc链接
        Connection connection = DriverManager.getConnection("jdbc:phoenix:master,node1,node2:2181");

        //2、编写sql查询数据
        PreparedStatement stat = connection.prepareStatement("select * from \"student\" where id=?");

        //3、设置参数
        stat.setString(1, "1500100992");

        //4、执行查询
        ResultSet resultSet = stat.executeQuery();

        //5、解析数据
        //如果返回的数据只有一条可以使用if,如果有多条使用while
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            String name = resultSet.getString("name");
            String age = resultSet.getString("age");
            String gender = resultSet.getString("gender");
            String clazz = resultSet.getString("clazz");
            System.out.println(id + "\t" + name + '\t' + age + "\t" + gender + "\t" + clazz);
        }

        //6、关闭链接
        stat.close();
        connection.close();
    }

    @Test
    public void insert()throws Exception{
        //1、建立jdbc链接
        Connection connection = DriverManager.getConnection("jdbc:phoenix:master,node1,node2:2181");

        //2、编写插入数据sql
        PreparedStatement stat = connection.prepareStatement("upsert into STUDENT values(?,?,?,?,?)");

        //3、设置参数
        stat.setString(1,"1500100010");
        stat.setString(2,"沈德昌");
        stat.setLong(3,21);
        stat.setString(4,"男");
        stat.setString(5,"理科一班");

        //4、执行插入
        stat.executeUpdate();

        //提交事务
        connection.commit();
        stat.close();


    }

}
